﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class ArrayPoolEx<T>
{
    public static Dictionary<int, Queue<T[]>> sizeQueueMap = new Dictionary<int, Queue<T[]>>();

    public static int GetArrayCount()
    {
        int c = 0;
        Dictionary<int, Queue<T[]>>.Enumerator e = sizeQueueMap.GetEnumerator();
        while (e.MoveNext())
        {
            c += e.Current.Value.Count;
        }

        return c;
    }

    public static int GetArrayElementCount()
    {
        int c = 0;
        Dictionary<int, Queue<T[]>>.Enumerator e = sizeQueueMap.GetEnumerator();
        while (e.MoveNext())
        {
            c += e.Current.Key * e.Current.Value.Count;
        }

        return c;
    }

    public static T[] Create(int size, bool fixSize = false)
    {
        if (size <= 0)
        {
            return null;
        }

        if(!fixSize)
        {
            if (!Mathf.IsPowerOfTwo(size))
            {
                size = Mathf.NextPowerOfTwo(size);
            }
        }

        Queue<T[]> q = null;
        if (!sizeQueueMap.TryGetValue(size, out q))
        {
            q = new Queue<T[]>();
            sizeQueueMap.Add(size, q);
        }

        if (q.Count > 0)
        {
            T[] t = q.Dequeue();
            return t;
        }
       
        return new T[size];
    }

    public static void Recycle(T[] a)
    {
        if (a == null)
        {
            return;
        }

        // Queue<T[]> q = null;
        // if (!sizeQueueMap.TryGetValue(a.Length, out q))
        // {
        //     q = new Queue<T[]>();
        //     sizeQueueMap.Add(a.Length, q);
        // }

        // for(int i = 0; i < a.Length; i++)
        // {
        //     a[i] = default(T);
        // }

        // q.Enqueue(a);
    }
}